package com.zhitan.ems.app.patrol.controller;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zhitan.ems.app.patrol.entity.PatrolEntity;
import com.zhitan.ems.app.patrol.entity.PatrolNoticeEntity;
import com.zhitan.ems.app.patrol.entity.PatrolTrackEntity;
import com.zhitan.ems.app.patrol.service.PatrolNoticeService;
import com.zhitan.ems.app.patrol.service.PatrolService;
import com.zhitan.ems.app.patrol.service.PatrolTrackService;
import com.zhitan.ems.app.patrol.vo.PatrolStatVo;
import com.zhitan.ems.app.patrol.vo.PatrolVO;
import com.zhitan.ems.app.patrol.wrapper.PatrolWrapper;
import com.zhitan.ems.common.core.controller.BaseController;
import com.zhitan.ems.common.core.domain.R;
import com.zhitan.ems.common.core.domain.entity.SysUser;
import com.zhitan.ems.common.extra.utils.MapUtils;
import com.zhitan.ems.common.utils.DateUtils;
import com.zhitan.ems.common.utils.StringUtils;
import com.zhitan.ems.framework.core.vo.VPage;
import com.zhitan.ems.framework.core.vo.VQueryKit;
import com.zhitan.ems.system.service.ISysUserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
/**
 * 巡检项目
 * @author zhitan
 * 
 * @date 2024-11-02 14:05:23
 */
@Api(tags = "PC管理--巡检--巡检计划", value = "巡检计划")
@RestController
@RequestMapping("intra/patrol/patrol")
public class PatrolController extends BaseController{
    @Autowired
    private PatrolService patrolService;
    @Autowired
   	private ISysUserService sysUserService;
    @Autowired
    private PatrolTrackService patrolTrackService;
    @Autowired
    private PatrolNoticeService patrolNoticeService;
//    @ApiOperation(value = "列表所有用户", response = VPage.class)
//    @ApiImplicitParams({
//		        @ApiImplicitParam(name = "name", value = "标题",  paramType = "query", required = false, dataType =  "String"),
//		})
//    @GetMapping("/listAllUser")
//    public R<List<SysUser>> listAllUser(@RequestParam Map<String, Object> params){
//         QueryWrapper<SysUser> queryWrapper=VQueryKit.getQueryWrapperByMap(params,Arrays.asList("name"), SysUser.class);
// 		queryWrapper.like(StringUtils.isNotNull(params.get("name")),"nick_name", params.get("name"));
// 		List<SysUser> list = sysUserAllMapper.selectList(queryWrapper);
// 		return R.data(list);
//    }
    /**
     * 列表
     */
    @ApiOperation(value = "列表", response = VPage.class)
    @ApiImplicitParams({
		        @ApiImplicitParam(name = "name", value = "标题",  paramType = "query", required = false, dataType =  "String"),
		})
    @GetMapping("/list")
    public R<VPage<PatrolVO>> list(@RequestParam Map<String, Object> params){
        QueryWrapper<PatrolEntity> queryWrapper=VQueryKit.getQueryWrapperByMap(params,Arrays.asList("name"), PatrolEntity.class);
        queryWrapper.orderByDesc("id");
         queryWrapper.like(StringUtils.isNotNull(params.get("name")),"name", params.get("name"));
         if(StringUtils.isNotNull(params.get("startDate"))&&StringUtils.isNotNull(params.get("endDate"))) {
             queryWrapper.between("create_at",
                     DateUtils.getStartOfDate(DateUtils.strToDate(params.get("startDate").toString())),
                     DateUtils.getEndOfDate(DateUtils.strToDate(params.get("endDate").toString()))
               );   
         }
        IPage<PatrolEntity> pages = patrolService.page(VQueryKit.getPage(params), queryWrapper);
        return R.data(PatrolWrapper.build().toVPageVO(pages));
    }
    @GetMapping("/listStat")
    public R<Map<String, Object>> listStat(@RequestParam Map<String, Object> params)throws ParseException{
         QueryWrapper<PatrolEntity> queryWrapper=VQueryKit.getQueryWrapperByMap(params,Arrays.asList("name"), PatrolEntity.class);
         queryWrapper.select("count(id) as total,sum(id) as all");
         queryWrapper.like(StringUtils.isNotNull(params.get("name")),"name", params.get("name"));
        if(params.containsKey("createDate")) {
            queryWrapper.between("create_at",
                    DateUtils.getStartOfDate(DateUtils.str_ToDate(params.get("createDate").toString())),
                    DateUtils.getEndOfDate(DateUtils.str_ToDate(params.get("createDate").toString()))
              );   
        }
        Map<String, Object>  stat=patrolService.getMap(queryWrapper);
        return R.data(stat);
    }
    @ApiOperation(value = "统计巡查", response = Map.class)
    @GetMapping("/queryStat")
    @PreAuthorize("@ss.hasPermi('patrol:patrol:list')")
    public R<Map<String, Object>> queryStat(@RequestParam Map<String, Object> params)throws ParseException{
         QueryWrapper<PatrolEntity> queryWrapper=VQueryKit.getQueryWrapperByMap(params,Arrays.asList("name"), PatrolEntity.class);
         queryWrapper.select("count(id) as total,sum(if(state=0,1,0)) as state1, sum(if(state=1,1,0)) as state0 ");
        if(params.containsKey("startDate")&&params.containsKey("endDate")) {
            queryWrapper.between("create_at",
                    DateUtils.getStartOfDate(DateUtils.strToDate(params.get("startDate").toString())),
                    DateUtils.getEndOfDate(DateUtils.strToDate(params.get("endDate").toString()))
              );   
         }
        Map<String, Object>  stat=patrolService.getMap(queryWrapper);
        return R.data(stat);
    }
    
    @ApiOperation(value = "按照人员统计巡查", response = PatrolStatVo.class)
    @GetMapping("/queryUserStat")
    @PreAuthorize("@ss.hasPermi('patrol:patrol:list')")
    public R<VPage<PatrolStatVo>> queryUserStat(@RequestParam Map<String, Object> params)throws ParseException{
    	QueryWrapper<PatrolEntity> queryWrapper=VQueryKit.getQueryWrapperByMap(params,Arrays.asList("name"), PatrolEntity.class);
        queryWrapper.select("user_id as userId,user_name as userName,count(id) as total,sum(if(state=0,1,0)) as state1, sum(if(state=1,1,0)) as state0 ");
        if(StringUtils.isNotNull(params.get("startDate"))&&StringUtils.isNotNull(params.get("endDate"))) {
           queryWrapper.between("create_at",
                   DateUtils.getStartOfDate(DateUtils.strToDate(params.get("startDate").toString())),
                   DateUtils.getEndOfDate(DateUtils.strToDate(params.get("endDate").toString()))
             );   
        }
       queryWrapper.groupBy("user_id","user_name");
       queryWrapper.orderByDesc("total");
//       List<Map<String, Object>> stat=patrolService.listMaps(queryWrapper);
       IPage<Map<String, Object>> statPage=patrolService.pageMaps(VQueryKit.getPage(params),queryWrapper);
       
       List<PatrolStatVo> patrolStatVos=new ArrayList<PatrolStatVo>();
       
       if(statPage.getRecords()!=null&&statPage.getRecords().size()>0) {
    	   QueryWrapper<PatrolNoticeEntity> queryNoticeWrapper=VQueryKit.getQueryWrapperByMap(params,Arrays.asList("name"), PatrolNoticeEntity.class);
	       queryNoticeWrapper.select("user_id as userId,user_name as userName,count(id) as total,sum(if(state=0,1,0)) as state1, sum(if(state=1,1,0)) as state0 ");
	       if(StringUtils.isNotNull(params.get("startDate"))&&StringUtils.isNotNull(params.get("endDate"))) {
	       	queryNoticeWrapper.between("create_at",
	                   DateUtils.getStartOfDate(DateUtils.strToDate(params.get("startDate").toString())),
	                   DateUtils.getEndOfDate(DateUtils.strToDate(params.get("endDate").toString()))
	             );   
	        }
	       queryNoticeWrapper.groupBy("user_id","user_name");
	       List<Map<String, Object>> noticeStat=patrolNoticeService.listMaps(queryNoticeWrapper);
	       HashMap<Integer, PatrolStatVo> noticeMap=new HashMap<Integer, PatrolStatVo>();
	       for(Map<String, Object> item:noticeStat) {
	       	Integer userId=MapUtils.getInteger("userId", item);
	       	PatrolStatVo patrolStatVo=new PatrolStatVo();
	       	patrolStatVo.setTotolNoticePreNum(MapUtils.getInteger("total", item));
	       	patrolStatVo.setTotolNoticeNum(MapUtils.getInteger("state1", item));
	       	noticeMap.put(userId, patrolStatVo);
	       }
	       for(Map<String, Object> item:statPage.getRecords()) {
	       	Integer userId=MapUtils.getInteger("userId", item);
	       	PatrolStatVo patrolStatVo=new PatrolStatVo();
	       	patrolStatVo.setUserId(MapUtils.getLong("userId", item));
	       	patrolStatVo.setUserName(MapUtils.getString("userName", item));
	       	patrolStatVo.setTotolPatrolPreNum(MapUtils.getInteger("total", item));
	       	patrolStatVo.setTotolPatrolNum(MapUtils.getInteger("state1", item));
	       	if(noticeMap.containsKey(userId)) {
	       		PatrolStatVo noticeStatVo=noticeMap.get(userId);
	       		if(noticeStatVo!=null) {
	       			patrolStatVo.setTotolNoticePreNum(noticeStatVo.getTotolNoticePreNum());
	       			patrolStatVo.setTotolNoticeNum(noticeStatVo.getTotolNoticeNum());
	       		}else {
	       			patrolStatVo.setTotolNoticePreNum(0);
	       			patrolStatVo.setTotolNoticeNum(0);
	       		}
	       	}else {
	       		patrolStatVo.setTotolNoticePreNum(0);
	   			patrolStatVo.setTotolNoticeNum(0);
	       	}
	       	patrolStatVos.add(patrolStatVo);
	       } 
       }
       VPage<PatrolStatVo> statVoPage= new VPage<PatrolStatVo>(patrolStatVos, statPage.getTotal(),statPage.getSize(),statPage.getCurrent());
        return R.data(statVoPage);
    }
    /**
     * 信息
     */
    @ApiOperation(value = "信息", response = PatrolVO.class)
    @GetMapping("/detail/{id}")
    @PreAuthorize("@ss.hasPermi('patrol:patrol:info')")
    public R<PatrolVO> detail(@PathVariable("id") Long id){
		PatrolEntity patrol = patrolService.getById(id);
		PatrolVO patrolVO=PatrolWrapper.build().entityVO(patrol);
		QueryWrapper<PatrolTrackEntity> queryWrapper=new QueryWrapper<>();
		queryWrapper.eq(VQueryKit.getUnderColumn("patrolId"), id);
		queryWrapper.orderByAsc("id");
		patrolVO.setPatrolTrackList(patrolTrackService.list(queryWrapper));
	    return R.data(patrolVO);
    }
     /**
     * 保存&更新
     */
    @ApiOperation(value = "保存&更新", response = Boolean.class)
    @PostMapping("/submit")
    @PreAuthorize("@ss.hasPermi('patrol:patrol:save')")
    public R<PatrolVO> submit(@Valid @RequestBody PatrolVO patrol){
   		if(patrol.getId()==null) {
            patrol.setCreateAt(new Date());
            patrol.setIsDelete(0);
            patrol.setUpdateAt(new Date());
            patrol.setNoticeReplayNum(0);
            patrol.setTrackNum(0);
        } 
   		if(patrol.getUserId()!=null) {
   			SysUser sysUser=sysUserService.selectUserById(patrol.getUserId());
   			if(sysUser!=null) {
   				patrol.setUserName(sysUser.getUserName());
   			}
   		}
    	if(patrolService.saveOrUpdate(patrol)) {
    		 return R.ok(patrol);
    	 }
    	return R.error("数据错误");
    }
    /**
     * 删除
     */
    @ApiOperation(value = "删除", response = Boolean.class)
    @DeleteMapping("/delete")
    @PreAuthorize("@ss.hasPermi('patrol:patrol:delete')")
    public R<Boolean> delete(@RequestBody Long[] ids){
        return R.ok(patrolService.removeByIds(Arrays.asList(ids)));
    }

}
